package com.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class SharedPreferencesActivity extends Activity {
	SharedPreferences preferencias;

	EditText etLogin;
	EditText etPassword;
	Spinner spinnerIdioma;
	CheckBox checkBoxKeepLoged;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		preferencias = getSharedPreferences("pepinillo", Context.MODE_PRIVATE);

		spinnerIdioma = (Spinner) findViewById(R.id.spinnerIdioma);
		etLogin = (EditText) findViewById(R.id.etLogin);
		etPassword = (EditText) findViewById(R.id.etPassword);
		checkBoxKeepLoged = (CheckBox) findViewById(R.id.checkBoxKeepLoged);

	}

	@Override
	protected void onStart() {
		super.onStart();
		UserDAO.init(this);

		restablecer(null);

	}

	public void guardar(View botonGuardar) {

		User user = new User();
		user.setId(1);
		user.setUsername(etLogin.getText().toString());
		user.setPassword(etPassword.getText().toString());

		SharedPreferences.Editor editor = preferencias.edit();
		// editor.putString("login", user.getUsername());
		// editor.putString("password", user.getPassword());
		editor.putInt("idioma", (int) spinnerIdioma.getSelectedItemId());
		editor.putBoolean("keepLoged", checkBoxKeepLoged.isChecked());
		editor.commit();

		if (UserDAO.getInstance().changeUser(user)) {
			Toast.makeText(this, "exito", Toast.LENGTH_SHORT).show();
		}
	}

	public void restablecer(View botonRestablecer) {
		UserDAO.init(this);

		User user = UserDAO.getInstance().getUser();
		if (user != null) {
			etLogin.setText(user.getUsername());
			etPassword.setText(user.getPassword());
		}

		// etLogin.setText(preferencias.getString("login", ""));
		// etPassword.setText(preferencias.getString("password", ""));
		spinnerIdioma.setSelection(preferencias.getInt("idioma", 0));
		checkBoxKeepLoged.setChecked(preferencias.getBoolean("keepLoged", false));

	}
}